package com.ming.security.service.impl;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

@Component
public class PasswordEncoderService implements PasswordEncoder {
    //加密
    @Override
    public String encode(CharSequence charSequence) {
        String algorithm = "md5";
        try {
            // 获取MessageDigest对象
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            // 获取明文字符串对应的字节数组
            byte[] input = ((String)charSequence).getBytes();
            // 执行加密
            byte[] output = messageDigest.digest(input);
            // 创建BigInteger对象
            int signum=1;
            BigInteger bigInteger = new BigInteger(signum, output);
            // 按照16进制将bigInteger转为字符串对象
            int radix=16;
            String encoded = bigInteger.toString(radix).toUpperCase();
            return encoded;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
    //对明文加密后和密文比较
    @Override
    public boolean matches(CharSequence charSequence, String s) {
        //明文加密
        String encode = encode(charSequence);
        //数据库密文
        String databasePassword=s;
        System.out.println("encode: "+encode);
        System.out.println("databasePassword: "+databasePassword);

        return Objects.equals(encode,databasePassword);
    }
}
